package com.hfzy.ihk.web.linkcall.controller.base;

import com.hfzy.ihk.common.util.http.HttpHelper;
import com.hfzy.ihk.common.util.image.CaptchaUtils;
import com.hfzy.ihk.common.util.string.StringUtil;
import com.hfzy.ihk.common.web.constants.WebConstant;
import com.hfzy.ihk.common.web.enums.LoginErrorMsgEnum;
import com.hfzy.ihk.facade.calldata.enums.PageFrom;
import com.hfzy.ihk.web.linkcall.utils.CallTaskUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/login")
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    /**
     * 这里注意，登录验证默认调用的方法为login,即验证方法（这个是框架默认的），如果不成功会回到此方法
     * @param request
     * @return
     */
    @RequestMapping(value = {"/redirectLoginPage"})
    public ModelAndView login(HttpServletRequest request,HttpServletResponse response) {
        return loginPage(request,response);
    }

    @RequestMapping(value = {"/loginPage","/"})
    public ModelAndView loginPage(HttpServletRequest request, HttpServletResponse response) {

        if (HttpHelper.isAjaxRequest(request)) {
            //没登录的情况下如果是ajax进来则调回登录页面
            try {
                response.getWriter().print("timeout");  //设置超时标识
                response.getWriter().close();
            } catch (IOException e) {
                logger.error("异常：",e);
            }
        }
        return new ModelAndView("loginPage");
    }



    /**
     * 生成验证码
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);

        //随机生成字符串，并写入session
        String code = CaptchaUtils.getRandCode(4);

        BufferedImage image = CaptchaUtils.getImage(100,30, code, 5);

        session.removeAttribute(WebConstant.VALIDATE_CODE);
        session.setAttribute(WebConstant.VALIDATE_CODE, code);

        // 将内存中的图片通过流动形式输出到客户端
        ImageIO.write(image, "JPEG", response.getOutputStream());
        return;
    }



    /**
     * 登录失败默认跳转接口 这个是可配置的，在conf中配
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/login/failure", method = RequestMethod.GET)
    public Map<String, Object> loginFailure(HttpServletRequest request, HttpServletResponse response) {
        AuthenticationException ae = (AuthenticationException) request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
        Map<String, Object> result = new HashMap<String, Object>();
        String message = ae.getMessage();
        result.put("success", false);
        if(StringUtil.isNotNull(message)&&LoginErrorMsgEnum.isDefined(message)){
            result.put("message", LoginErrorMsgEnum.fromKey(message));
        }else if(StringUtil.isNotEmpty(message)&&message.equals("Bad credentials")){
            result.put("message", LoginErrorMsgEnum.PASSWORD_NOT_FIND.getDesc());
        }else{
            result.put("message", LoginErrorMsgEnum.LOGIN_FAIL.getDesc());
        }
        return result;
    }


    /**
     * 登录成功默认跳转的接口，这个在conf中配置
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/login/success", method = RequestMethod.GET)
    public Map<String, Object> loginSuccess(HttpServletRequest request, HttpServletResponse response) {
        //登陆成功将 user 放入session
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", true);
        result.put("message", LoginErrorMsgEnum.SUCCESS.toStr());
        return result;
    }

    @RequestMapping("/index")
    public String index(Model model) {
        model.addAttribute("connectWsVo", CallTaskUtils.getConnectWsVo("33", PageFrom.PC_AI_CALL.getValue(),"3"));
        model.addAttribute("pageFrom",PageFrom.PC_AI_CALL.getValue());
        return "page/main";
    }


}
